import React, { useState } from "react";
import { Form, Input, Button, Toast } from "react-vant";
import { getEmailCodeApi, registerApi } from "../../../api/myApi";
import { RegisterState } from "../../../types";
const emeailReg =
  /^(([^<>()[\]\\.,;:\s@"]+(\.[^<>()[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
const Index: React.FC = () => {
  const [email, setEmail] = useState("");
  const [code, setCode] = useState("");
  const getCode = async () => {
    if (!email) return Toast.fail("邮箱不可以为空");

    if (!emeailReg.test(email)) return Toast.fail("邮箱格式不正确");

    // 发送邮箱
    const data = await getEmailCodeApi(email);

    if (data.status === "0000") {
      Toast.success("验证码发送成功");
    }
  };

  const onFinish = (value: RegisterState) => {
    if (value.pwd1 !== value.pwd2) return Toast.fail("两次密码不一致");
    registerApi(value);
  };
  const onFinishFailed = () => {};
  return (
    <div>
      <Form
        onFinish={onFinish}
        onFinishFailed={onFinishFailed}
        footer={
          <div style={{ margin: "16px 16px 0" }}>
            <Button round nativeType="submit" type="primary" block>
              提交
            </Button>
          </div>
        }
      >
        <Form.Item
          name="email"
          label="邮箱"
          rules={[
            { pattern: emeailReg, message: "邮箱格式不正确", required: true },
          ]}
        >
          <Input
            // value={email}
            // onChange={(value) => setEmail(value)}
            suffix={
              <Button type="primary" size="mini" onClick={() => getCode()}>
                获取验证码
              </Button>
            }
          ></Input>
        </Form.Item>
        <Form.Item
          name="code"
          label="验证码"
          rules={[
            { pattern: /\d{6}/, message: "验证码不正确", required: true },
          ]}
        >
          <Input value={code} onChange={(value) => setCode(value)}></Input>
        </Form.Item>
        <Form.Item
          name="pwd1"
          label="密码"
          rules={[{ message: "密码不可以为空", required: true }]}
        >
          <Input></Input>
        </Form.Item>
        <Form.Item
          name="pwd2"
          label="重复密码"
          rules={[{ message: "密码不可以为空", required: true }]}
        >
          <Input></Input>
        </Form.Item>
        <Form.Item name="invitationCode" label="邀请码">
          <Input></Input>
        </Form.Item>
      </Form>
    </div>
  );
};

export default Index;
